<!-- eslint-disable unused-imports/no-unused-vars -->
<script setup lang="ts">
import type { PositionApplication } from "../position/apis/type"
import { usePagination } from "@@/composables/usePagination"
import { Search } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { computed, reactive, ref } from "vue"
import { getPositionApplicationsApi, reviewPositionApplicationApi } from "../position/apis/position"

const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const applicationsList = ref<PositionApplication[]>([])
const reviewDialogVisible = ref(false)
const currentApplication = ref<PositionApplication | null>(null)
const reviewFormRef = ref()

// 搜索表单
const searchForm = reactive({
  positionName: "",
  studentName: "",
  status: ""
})

// 审核表单
const reviewForm = reactive({
  status: "",
  comment: ""
})

// 审核表单验证规则
const reviewRules = {
  status: [
    { required: true, message: "请选择审核结果", trigger: "change" }
  ],
  comment: [
    {
      validator: (rule: any, value: string, callback: (error?: Error) => void) => {
        if (reviewForm.status === "rejected" && !value) {
          callback(new Error("请输入驳回理由"))
        } else {
          callback()
        }
      },
      trigger: "blur"
    }
  ]
}

// 计算分页后的数据
const applicationsData = computed(() => {
  return applicationsList.value
})

// 获取申请列表
async function getApplications() {
  loading.value = true
  try {
    const query = {
      currentPage: paginationData.currentPage,
      size: paginationData.pageSize
    }
    if (searchForm.status) {
      Object.assign(query, { status: searchForm.status })
    }

    const { data } = await getPositionApplicationsApi(query)
    paginationData.total = data.total
    applicationsList.value = data.list
  } catch (_error) {
    ElMessage.error("获取申请列表失败")
    applicationsList.value = []
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  paginationData.currentPage = 1
  getApplications()
}

// 重置搜索
function resetSearch() {
  Object.assign(searchForm, {
    positionName: "",
    studentName: "",
    status: ""
  })
  handleSearch()
}

// 处理审核
function handleReview(application: PositionApplication) {
  currentApplication.value = application
  reviewForm.status = ""
  reviewForm.comment = ""
  reviewDialogVisible.value = true
}

// 查看详情
function viewDetail(application: PositionApplication) {
  currentApplication.value = application
  reviewForm.status = application.status
  reviewForm.comment = application.reviewComment || ""
  reviewDialogVisible.value = true
}

// 提交审核
async function submitReview() {
  await reviewFormRef.value.validate()
  if (!currentApplication.value) return

  loading.value = true
  try {
    await reviewPositionApplicationApi(currentApplication.value.id!, {
      status: reviewForm.status as "approved" | "rejected",
      comment: reviewForm.comment
    })
    ElMessage.success("审核成功")
    reviewDialogVisible.value = false
    getApplications()
  } catch (error) {
    ElMessage.error("审核失败")
  } finally {
    loading.value = false
  }
}

// 格式化日期
function formatDate(dateString?: string) {
  if (!dateString) return ""
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`
}

// 获取状态标签
function getStatusLabel(status: string) {
  const statusMap = {
    pending: "待审核",
    approved: "已通过",
    rejected: "已驳回"
  }
  return statusMap[status as keyof typeof statusMap] || status
}

// 获取状态标签类型
function getStatusTagType(status: string): "warning" | "success" | "danger" | "info" {
  const typeMap = {
    pending: "warning",
    approved: "success",
    rejected: "danger"
  } as const
  return typeMap[status as keyof typeof typeMap] || "info"
}

// 初始化
getApplications()
</script>

<template>
  <div class="application-review-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>岗位申请审核</span>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="岗位名称">
          <el-input v-model="searchForm.positionName" placeholder="输入岗位名称" />
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input v-model="searchForm.studentName" placeholder="输入学生姓名" />
        </el-form-item>
        <el-form-item label="申请状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px;">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <Search /> 搜索
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 申请列表 -->
      <el-table v-loading="loading" :data="applicationsData" style="width: 100%">
        <el-table-column prop="positionName" label="岗位名称" width="180" />
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="major" label="专业" width="150" />
        <el-table-column prop="applyTime" label="申请时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="expectedStartDate" label="预计入职时间" width="150" />
        <el-table-column prop="status" label="申请状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 'pending'"
              type="primary"
              size="small"
              @click="handleReview(scope.row)"
            >
              审核
            </el-button>
            <el-button v-else size="small" @click="viewDetail(scope.row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="paginationData.currentPage"
        v-model:page-size="paginationData.pageSize"
        layout="prev, pager, next, jumper"
        :total="paginationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog v-model="reviewDialogVisible" title="岗位申请审核" width="600px">
      <div v-if="currentApplication" class="review-content">
        <h3>申请信息</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="岗位名称">
            {{ currentApplication.positionName }}
          </el-descriptions-item>
          <el-descriptions-item label="学生姓名">
            {{ currentApplication.studentName }}
          </el-descriptions-item>
          <el-descriptions-item label="专业">
            {{ currentApplication.major }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDate(currentApplication.applyTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="预计入职时间">
            {{ currentApplication.expectedStartDate }}
          </el-descriptions-item>
          <el-descriptions-item label="预计结束时间">
            {{ currentApplication.expectedEndDate }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentApplication.contactPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="紧急联系人">
            {{ currentApplication.emergencyContact.name }} ({{ currentApplication.emergencyContact.phone }})
          </el-descriptions-item>
          <el-descriptions-item label="面试通过证明">
            <el-link :href="currentApplication.interviewProofUrl" target="_blank">
              查看证明文件
            </el-link>
          </el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px;">
          审核意见
        </h3>
        <el-form ref="reviewFormRef" :model="reviewForm" :rules="reviewRules" label-width="80px">
          <el-form-item label="审核结果" prop="status">
            <el-radio-group v-model="reviewForm.status">
              <el-radio label="approved">
                通过
              </el-radio>
              <el-radio label="rejected">
                驳回
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="reviewForm.status === 'rejected'"
            label="驳回理由"
            prop="comment"
          >
            <el-input
              v-model="reviewForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入驳回理由"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">提交审核</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.application-review-page {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .review-content {
    max-height: 500px;
    overflow-y: auto;
  }
}
</style>
